﻿using System.Collections.Generic;
using SqlSugar;
using Hiver.Util.Config;
using Hiver.Util.Config.Model;

namespace Hiver.Util.SqlServer.SqlSugar
{
    /// <summary>
    /// SqlSugar数据连接类
    /// </summary>
    public class SqlSugarConn
    {
        /// <summary>
        /// 数据库实例
        /// </summary>
        private static SqlSugarClient _instance = null;

        /// <summary>
        /// 获得数据库类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static DbType GetDbTypeByName(string type)
        {
            switch (type.ToLower())
            {
                case "mysql":
                    return DbType.MySql;
                case "sqlite":
                    return DbType.Sqlite;
                default:
                    return DbType.SqlServer;
            }
        }

        /// <summary>
        /// 单例模型
        /// </summary>
        /// <returns></returns>
        public static SqlSugarClient GetInstance()
        {
            if (_instance == null)
            {
                // 加载默认配置
                ApplicationConfigModel config = YamlHelper<ApplicationConfigModel>.Load();
                if (config == null)
                    Error.Show(1);
                // 加载数据库配置
                if (config.Sugar == null || config.Sugars == null || config.Sugars.Count == 0)
                    Error.Show(2);
                if (config.Sugar != null)
                {
                    // 默认使用单数据库连接
                    _instance = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = config.Sugar.ConnectionString,
                        DbType = GetDbTypeByName(config.Sugar.DbType),
                        IsAutoCloseConnection = config.Sugar.IsAutoCloseConnection,
                        InitKeyType = InitKeyType.Attribute
                    });
                }
                else
                {
                    // 单数据库配置不存在则使用多数据库连接
                    List<ConnectionConfig> list = new List<ConnectionConfig>();
                    foreach (Sugars sugar in config.Sugars)
                    {
                        list.Add(new ConnectionConfig()
                        {
                            ConfigId = sugar.Id,
                            ConnectionString = sugar.ConnectionString,
                            DbType = GetDbTypeByName(sugar.DbType),
                            IsAutoCloseConnection = sugar.IsAutoCloseConnection,
                            InitKeyType = InitKeyType.Attribute
                        });
                    }
                    _instance = new SqlSugarClient(list);
                }
            }
            return _instance;
        }
    }
}